package com.csi.config;

import com.github.pagehelper.PageInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.logging.slf4j.Slf4jImpl;
import org.apache.ibatis.session.AutoMappingBehavior;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import javax.sql.DataSource;
import java.util.Properties;

@Configuration
@Import(DataSourceConfig.class)
@Slf4j
public class MybatisConfig {

    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration() ;
        //这行代码配置了一个常见的 MyBatis 配置项，使得查询结果的列名（如 user_name）自动映射到 Java 对象的属性名（如 userName）。
        // 即 MyBatis 会将数据库中的下划线命名规则自动转换为 Java 对象的驼峰命名规则。
        configuration.setMapUnderscoreToCamelCase(true);
        configuration.setLogImpl(Slf4jImpl.class);
        configuration.setAutoMappingBehavior(AutoMappingBehavior.FULL);
        sqlSessionFactoryBean.setConfiguration(configuration);

        //resultType="userInfo"
        sqlSessionFactoryBean.setTypeAliasesPackage("com.csi.domain");

        PageInterceptor pageInterceptor = new PageInterceptor() ;

        Properties properties = new Properties() ;
        properties.setProperty("helperDialect","mysql") ;
        pageInterceptor.setProperties(properties);
        sqlSessionFactoryBean.setPlugins(pageInterceptor);
        return sqlSessionFactoryBean ;

    }

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer() ;
        mapperScannerConfigurer.setBasePackage("com.csi.mapper");
        return mapperScannerConfigurer ;
    }

}
